package com.springboot.learn_zookeeper.demo2;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.util.List;

/**
 * 删除节点
 */
public class ZKDelete {
    private static ZooKeeper zk;
    private static ZooKeeperConnection conn;

    // Method to check existence of znode and its status, if znode is available.
    public static void delete(String path) throws KeeperException,InterruptedException {
        zk.delete(path,zk.exists(path,true).getVersion());
    }
    public static Stat znode_exists(String path) throws
            KeeperException,InterruptedException {
        return zk.exists(path,true);
    }

    public static void main(String[] args) throws InterruptedException,KeeperException {
        String path = "/MyFirstZnode"; //Assign path to the znode

        try {
            conn = new ZooKeeperConnection();
            zk = conn.connect("localhost");
            Stat stat = znode_exists(path); // Stat checks the path

            if(stat!= null) {
                List<String> children = zk.getChildren(path, false);
                for (int i = 0; i < children.size(); i++) {
                    System.out.println(children.get(i)); //Print children's
                    Stat stat2 = znode_exists(path+"/"+children.get(i));
                    if(stat2!=null){
                        delete(path+"/"+children.get(i));
                    }
                }
                delete(path);
            }else{
                System.out.println("Node does not exists");
            }
        } catch(Exception e) {
            System.out.println(e.getMessage()); // catches error messages
        }
    }
}
